﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.Composition;
using System.Net;
using System.Net.Mime;
using System.Text;
using UnfriendlyFire.BingServices;

namespace UnfriendlyFire.Controllers
{
    [Export(typeof(IController))]
    [ExportMetadata("Name", "Services")]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
    public class ServicesController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ReverseGeocode(double? latitude, double? longitude)
        {
            double lat = latitude == null ? 0.0 : latitude.Value;
            double lon = longitude == null ? 0.0 : longitude.Value;
            var request = new ReverseGeocodeRequest()
            {
                Location = new Location()
                {
                    Latitude = lat,
                    Longitude = lon
                },
                Credentials = new Credentials()
                {
                    ApplicationId = "AiuRCpa5CkvXPDhMn4hfQ3whVE3qK4WvMeWq8SOdnbXw_gDHjT5C405AYAW_GoZf",
                },
            };

            var client = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            GeocodeResponse response = client.ReverseGeocode(request);
            return Json(response, JsonRequestBehavior.AllowGet);
            
            //double lat = latitude == null ? 0.0 : latitude.Value;
            //double lon = longitude == null ? 0.0 : longitude.Value;
            //string url = string.Format("http://maps.google.com/maps/api/geocode/json?latlng={0},{1}&sensor=false", lat, lon);
            //WebRequest request = WebRequest.Create(url);
            //WebResponse response = request.GetResponse();
            //var stream = response.GetResponseStream();
            //int bufferOffset = 0;
            //byte[] buffer = new byte[1024];
            //byte[] tempBuffer = new byte[1024];
            //int bytesRead = 0;
            //while ((bytesRead = stream.Read(tempBuffer, 0, 1024)) > 0)
            //{
            //    if (bufferOffset + bytesRead > buffer.Length)
            //    {
            //        byte[] newBuffer = new byte[bufferOffset + bytesRead];
            //        buffer.CopyTo(newBuffer, 0);
            //        buffer = newBuffer;
            //    }
            //    Buffer.BlockCopy(tempBuffer, 0, buffer, bufferOffset, bytesRead);
            //    bufferOffset += bytesRead;
            //}
            //var script = Encoding.UTF8.GetString(buffer);
            //return File(buffer, "application/json");
        }
    }
}
